﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.Collections.ObjectModel;

namespace Passwords.Models
{
    [DataContract(Namespace = "http://schemas.datacontract.org/2004/07/PasswordsService")]
    public class CategoryContract : Entity
    {
        [DataMember]
        public string Id { get; set; }

        public string Name
        {
            get { return string.IsNullOrEmpty(name) ? "" : name; }
            set
            {
                if (name != value)
                {
                    name = value;
                    OnPropertyChanged("Name");
                }
            }
        }

        [DataMember(Name = "Fields")]
        public FieldContract[] TransferFields { get; set; }

        [DataMember]
        public DateTime Modified { get; set; }

        [DataMember]
        public bool IsSynced { get; set; }

        [DataMember(Name="Name")]
        private string name;

        [IgnoreDataMember]
        private ObservableChildCollection<FieldContract> fields;

        [IgnoreDataMember]
        private ObservableChildCollection<PasswordContract> passwords;


        [IgnoreDataMember]
        public bool IsNew
        {
            get { return string.IsNullOrEmpty(Id); }
        }

        [IgnoreDataMember]
        public bool IsTemplate
        {
            get { return TransferFields != null && TransferFields.Length > 0; }
        }



        [IgnoreDataMember]
        public ObservableChildCollection<FieldContract> Fields
        {
            get
            {
                return fields ?? (fields = CreateFields());
            }
        }



        [IgnoreDataMember]
        public ObservableChildCollection<PasswordContract> Passwords
        {
            get
            {
                if (passwords == null)
                {
                    passwords = new ObservableChildCollection<PasswordContract>(this);
                }
                return passwords;
            }
        }

        private void UnsetFieldsModified()
        {
                foreach (FieldContract field in Fields) field.IsModified = false;
        }

        private bool CheckFieldsModified()
        {
            if (Fields.Any(f => f.IsModified)) return true;
            return false;
        }

        public override string ToString()
        {
            return Name + ", " + Id;
        }

        private ObservableChildCollection<FieldContract> CreateFields()
        {
            var fields = TransferFields;
            ObservableChildCollection<FieldContract> result = fields != null ?
                new ObservableChildCollection<FieldContract>(this, fields)
                :
                new ObservableChildCollection<FieldContract>(this);

            return result;
        }


    }
}
